package com.pride1952.myoptimusx3;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.ColorMatrixColorFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener,ContactFragment.OnFragmentInteractionListener{

    /**
     * 按下这个按钮进行的颜色过滤
     */
    public final static float[] SELECTED=new float[] {
            1, 0, 0, 0, 0,
            0, 1, 0, 0, 50,
            0, 0, 1, 0, 100,
            0, 0, 0, 1, 0 };

    /**
     * 按钮恢复原状的颜色过滤
     */
    public final static float[] NOT_SELECTED=new float[] {
            1, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 1, 0, 0,
            0, 0, 0, 1, 0 };

    private ImageButton mBtnRing;
    private ImageButton mBtnContact;
    private ImageButton mBtnExplore;
    private ImageButton mBtnMe;
    private ImageButton mBtnPlus;

    private TitleFragment mTitle;
    private RingFragment mRing;
    private ContactFragment mContact;
    private ExploreFragment mExplore;
    private MeFragment mMe;

    private int currSelBtns;
    public static String state ="";

    public static final int REQUEST_ENABLE_BT = 123;
    public static final int REQUEST_SCAN_DEVICE = 124;

    private PopupWindow mPopPlusMenu=null;
    private PopupWindow mPopWaiting=null;
    private PopupWindow mPopResultOfCard=null;

    private final static String TAG = MainActivity.class.getSimpleName();
    public static BluetoothLeService mBluetoothLeService;

    private IntentFilter intentFilter(){
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(BluetoothLeService.mACTION_REQUEST_ENABLE_BT);
        intentFilter.addAction(BluetoothLeService.mACTION_REQUEST_SCAN_DEVICE);
        intentFilter.addAction(BluetoothLeService.mACTION_BALANCE_READ);
        intentFilter.addAction(BluetoothLeService.mACTION_BLUETOOTH_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.mACTION_BALANCE_NOT_READ);
        intentFilter.addAction(BluetoothLeService.mACTION_DEVICE_CONNECT_FAILED);
        return intentFilter;
    }
    private BroadcastReceiver bcReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action)
            {
                case BluetoothLeService.mACTION_REQUEST_ENABLE_BT:
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    break;

                case BluetoothLeService.mACTION_REQUEST_SCAN_DEVICE:
                    startActivityForResult(new Intent(MainActivity.this, ScanNewDevicesActivity.class), REQUEST_SCAN_DEVICE);
                    break;


                case BluetoothLeService.mACTION_BALANCE_READ:
                    if(mPopWaiting!=null){
                        mPopWaiting.dismiss();
                        Log.i(TAG, "关闭提示框");
                    }
                    //处理读卡，通过intent.getFloatExtra("balance"，0)得到float类型的余额值
                    float balance=intent.getFloatExtra("balance",-1f);
                    String resultStr="余额："+Float.toString(balance)+"元";
                    if(balance==-1f)
                    {
                        resultStr="读卡失败！请重试";
                    }
                    mPopResultOfCard=initPopShow(R.mipmap.yuan,resultStr,true);
                    mPopResultOfCard.getContentView().setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPopResultOfCard.dismiss();
                        }
                    });
                    break;

                case BluetoothLeService.mACTION_BALANCE_NOT_READ:
                    if(mPopWaiting!=null)
                        mPopWaiting.dismiss();
                    Toast.makeText(getApplicationContext(),"未发现卡片，请重试",Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }
        }
    };

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            Log.i(TAG, "onServiceConnected called.");
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            mBluetoothLeService.connectDevice();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Toast.makeText(getApplicationContext(),"连接中断",Toast.LENGTH_SHORT).show();
            Log.e(TAG,"Disconnected");
            mBluetoothLeService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //检测设备是否支持BLE，若否则直接结束。
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }
        initTitle();
        initServices();
        initWidgets();

        registerReceiver(bcReceiver,intentFilter());

        setDefaultFragment();
        initPopPlusMenu();
    }
    private void initServices(){
        startService(new Intent(MainActivity.this, NotificationService.class));
        startService(new Intent(MainActivity.this, BluetoothLeService.class));
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    private void initWidgets(){
        mBtnRing=(ImageButton)findViewById(R.id.imgbtn_ring);
        mBtnContact=(ImageButton)findViewById(R.id.imgbtn_contact);
        mBtnExplore=(ImageButton)findViewById(R.id.imgbtn_explore);
        mBtnMe=(ImageButton)findViewById(R.id.imgbtn_me);
        mBtnPlus=(ImageButton)findViewById(R.id.imgbtn_plus);

        mBtnRing.setOnClickListener(this);
        mBtnContact.setOnClickListener(this);
        mBtnExplore.setOnClickListener(this);
        mBtnMe.setOnClickListener(this);
        mBtnPlus.setOnClickListener(this);
    }

    private void initTitle(){
        FragmentManager fm=getFragmentManager();
        FragmentTransaction transaction=fm.beginTransaction();
        Bundle bundle=new Bundle();
        bundle.putString("Title","AirBand");
        bundle.putBoolean("IsBack",false);
        mTitle=new TitleFragment();
        mTitle.setArguments(bundle);
        transaction.replace(R.id.title_main, mTitle);
        transaction.commit();
    }

    @Override
    protected void onDestroy(){
        unbindService(mServiceConnection);
        unregisterReceiver(bcReceiver);
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_SCAN_DEVICE && resultCode == Activity.RESULT_OK){
            //mBluetoothLeService.connectDevice();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setDefaultFragment()
    {
        mBtnRing.getBackground().setColorFilter(new ColorMatrixColorFilter(SELECTED));
        mBtnRing.setBackground(mBtnRing.getBackground());
        mBtnContact.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
        mBtnContact.setBackground(mBtnContact.getBackground());
        mBtnMe.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
        mBtnMe.setBackground(mBtnMe.getBackground());

        FragmentManager fm=getFragmentManager();
        FragmentTransaction trasaction=fm.beginTransaction();
        mRing=new RingFragment();
        trasaction.replace(R.id.body, mRing);
        trasaction.commit();
        currSelBtns=0;
    }

    private void initPopPlusMenu()
    {
        View view=this.getLayoutInflater().inflate(R.layout.popupwindow_plusmenu,null);
        mPopPlusMenu=new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        //刷卡按钮
        ImageButton mImgBtnSwingCard=(ImageButton)view.findViewById(R.id.imgbtn_plusmenu_swingcard);
        mImgBtnSwingCard.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBluetoothLeService.isReady()) {
                    mPopWaiting = initPopShow(R.mipmap.waiting_swing_card, "请将卡片靠近手环", true);
                    mPopWaiting.getContentView().setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mBluetoothLeService.doStopReadBalance();
                            mPopWaiting.dismiss();
                        }
                    });
                    mBluetoothLeService.doReadBalance();

                } else {
                    if (mBluetoothLeService.isDeviceConnected()) {
                        if (mBluetoothLeService.isDeviceBusy())
                            Toast.makeText(getApplicationContext(), "正在同步，请稍后操作", Toast.LENGTH_SHORT).show();
                    } else
                        Toast.makeText(getApplicationContext(), "请先连接手环", Toast.LENGTH_SHORT).show();

                }
            }
        });
        //添加新设备按钮
        ImageButton mImgBtnAddDevice=(ImageButton)view.findViewById(R.id.imgbtn_plusmenu_add_devices);
        mImgBtnAddDevice.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(MainActivity.this, ScanNewDevicesActivity.class), REQUEST_SCAN_DEVICE);

            }
        });
        //修改密码按钮
        ImageButton mImgBtnChangePassword=(ImageButton)view.findViewById(R.id.imgbtn_plusmenu_change_password);
        mImgBtnChangePassword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setDialogChangePsw();
            }
        });
        //
        mPopPlusMenu.setOutsideTouchable(true);
        mPopPlusMenu.setTouchable(true);

        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopPlusMenu.dismiss();
            }
        });
    }

    private void setDialogChangePsw(){
        //弹出填写密码的dialog
        final EditText mEditPsw=new EditText(MainActivity.this);
        mEditPsw.setInputType(InputType.TYPE_CLASS_NUMBER);
        mEditPsw.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("请输入四位旧密码")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(mEditPsw)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String oriPsw = mEditPsw.getText().toString();
                                mEditPsw.setText("");
                                if (mBluetoothLeService.doCheckPassword(oriPsw)) {
                                    new AlertDialog.Builder(MainActivity.this)
                                            .setTitle("请输入四位新密码")
                                            .setIcon(android.R.drawable.ic_dialog_info)
                                            .setView(mEditPsw)
                                            .setPositiveButton("确定",
                                                    new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            String newPsw=mEditPsw.getText().toString();
                                                            mBluetoothLeService.doChangePassword(newPsw);
                                                            Toast.makeText(getApplicationContext(),"密码已修改",Toast.LENGTH_SHORT).show();
                                                        }
                                                    })
                                            .setNegativeButton("取消",null)
                                            .show();
                                }
                                else{
                                    Toast.makeText(getApplicationContext(),"密码错误，请重新输入",Toast.LENGTH_SHORT).show();
                                    setDialogChangePsw();
                                }
                            }
                        })
                .setNegativeButton("取消", null)
                .show();
    }

    public PopupWindow initPopShow(int imageId,String text,boolean isTouchable)
    {
        View view2 = getLayoutInflater().inflate(R.layout.popupwindow_show, null);
        PopupWindow pop = new PopupWindow(view2, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.showAtLocation(findViewById(R.id.main), Gravity.CENTER_HORIZONTAL, 0, 0);
        pop.setOutsideTouchable(true);
        if(isTouchable) {
            TextView txtTip=(TextView)view2.findViewById(R.id.txt_pop_show_tip);
            txtTip.setVisibility(View.VISIBLE);
        }
        ImageView img=(ImageView)view2.findViewById(R.id.img_pop_show);
        img.setBackgroundResource(imageId);
        TextView txt=(TextView)view2.findViewById(R.id.txt_pop_show);
        txt.setText(text);
        return pop;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        FragmentManager fm=getFragmentManager();
        FragmentTransaction transaction=fm.beginTransaction();
        switch (v.getId())
        {
            case R.id.imgbtn_ring:
                mBtnRing.getBackground().setColorFilter(new ColorMatrixColorFilter(SELECTED));
                mBtnRing.setBackground(mBtnRing.getBackground());
                mBtnContact.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnContact.setBackground(mBtnContact.getBackground());
                mBtnExplore.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnExplore.setBackground(mBtnRing.getBackground());
                mBtnMe.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnMe.setBackground(mBtnMe.getBackground());

                if(mRing==null)
                {
                    mRing=new RingFragment();
                }
                transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right);
                currSelBtns=0;
                transaction.replace(R.id.body, mRing);
                break;
            case R.id.imgbtn_contact:
                mBtnRing.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnRing.setBackground(mBtnRing.getBackground());
                mBtnContact.getBackground().setColorFilter(new ColorMatrixColorFilter(SELECTED));
                mBtnContact.setBackground(mBtnContact.getBackground());
                mBtnExplore.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnExplore.setBackground(mBtnRing.getBackground());
                mBtnMe.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnMe.setBackground(mBtnMe.getBackground());

                if(mContact==null)
                {
                    mContact=new ContactFragment();
                }
                if(currSelBtns<1)
                {
                    transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left);
                }
                else
                {
                    transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right);
                }
                currSelBtns=1;
                transaction.replace(R.id.body, mContact);
                break;
            case R.id.imgbtn_explore:
                mBtnRing.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnRing.setBackground(mBtnRing.getBackground());
                mBtnContact.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnContact.setBackground(mBtnContact.getBackground());
                mBtnExplore.getBackground().setColorFilter(new ColorMatrixColorFilter(SELECTED));
                mBtnExplore.setBackground(mBtnRing.getBackground());
                mBtnMe.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnMe.setBackground(mBtnMe.getBackground());

                if(mExplore==null)
                {
                    mExplore=new ExploreFragment();
                }
                if(currSelBtns<2)
                {
                    transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left);
                }
                else
                {
                    transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right);
                }
                currSelBtns=2;
                transaction.replace(R.id.body, mExplore);
                break;
            case R.id.imgbtn_me:
                mBtnRing.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnRing.setBackground(mBtnRing.getBackground());
                mBtnContact.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnContact.setBackground(mBtnContact.getBackground());
                mBtnExplore.getBackground().setColorFilter(new ColorMatrixColorFilter(NOT_SELECTED));
                mBtnExplore.setBackground(mBtnRing.getBackground());
                mBtnMe.getBackground().setColorFilter(new ColorMatrixColorFilter(SELECTED));
                mBtnMe.setBackground(mBtnMe.getBackground());

                if(mMe==null)
                {
                    mMe=new MeFragment();
                }
                transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left);
                currSelBtns=3;
                transaction.replace(R.id.body,mMe);
                break;
            case R.id.imgbtn_plus:
                if(!mPopPlusMenu.isShowing())
                {
                    mPopPlusMenu.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,findViewById(R.id.bottombar).getHeight());
                }
                else
                {
                    mPopPlusMenu.dismiss();
                }
                break;
            default:
                mPopPlusMenu.dismiss();
                break;

        }
        //transaction.addToBackStack("replace");
        transaction.commit();
    }

    @Override
    public void onFragmentInteraction(String id) {

    }
}
